/*
 * @author : TF-BJ-C064
 * @creation : 2014-7-15 下午9:30:41
 * @description : 
 *
 */

package com.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.Cookie;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class HttpClientTest {

	public static Logger log = Logger.getLogger(HttpClientTest.class);

	/**
	 * <p>Title: main</p>
	 * <p>Description: </p>
	 * @param args
	 * @throws ClientProtocolException 
	 * @throws IOException 
	 * @throws HttpException 
	 */

	public static int i =0 ;
	public static String s = null;
	public static String usernames[]= new String[11000];
	public static void main(String[] args) throws ClientProtocolException, IOException  {

		HttpClientTest test = (new HttpClientTest());
		
		for(int i=1; i<2000; i++){
			test.setUsername("testtest-"+i);
		//		test.SJZYJQ(i);
		}
		

		File file = new File("F:\\1.txt");//Text文件
		BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
		while((s = br.readLine())!=null){//使用readLine方法，一次读一行
			if(s.trim()!=null)
			{
				usernames[i] =  s.split(" ")[0].trim();
			}
			i++;
		}
		br.close();
		
		log.info("readed usernames length="+usernames.length);
		for(i=0; i<usernames.length; i++){
			new Thread(){
				@Override  
				public void run() {  
					HttpClientTest test = (new HttpClientTest());
					test.setUsername( usernames[i]);
					try{
						test.SJZYJQ(i);
					}catch (Exception e) {
					} 
				}
			}.start();
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		br.close();;


	}

	String username = "karl"+ (int)(Math.random()*1000);
	String password = "0987654321";

	Header[] sessionID;
	String cookies;
	Map<String, String> postparams = new HashMap<String, String>();

	public void GetCookie(String codeUrl, int number) throws ClientProtocolException, IOException  {

		HttpClient httpclient = new DefaultHttpClient();
		HttpGet get = new HttpGet(codeUrl);
		HttpResponse httpResponse = httpclient.execute(get);
		String html = EntityUtils.toString(httpResponse.getEntity());
		//	log.info("httpResponse==\n" + html);
		//	log.info("--------------------- end of httpResponse-----------------------------");
		sessionID = httpResponse.getHeaders("Set-Cookie");
		this.setCookie(sessionID);
		get.releaseConnection();

		Document doc = Jsoup.parse(html);
		Element form = doc.select("form ").first();
		//	log.info("\n"+ form.html());
		//	log.info("------------------end of form---------------------------------");

		postparams.put( "regsubmit", "yes");
		postparams.put( "formhash", form.select("input[name=formhash]").first().attr("value"));
		postparams.put( "referer", Referer);
		postparams.put( "activationauth", "");
		postparams.put( "agreebbrule", "true");

		Element e = null;
		e = form.select("ul input[tabindex=1]").first();
		postparams.put( e.attr("name"), username);//username
		String url2 =
				"http://www.sjzyjq.com/forum.php?mod=ajax&inajax=yes&infloat=register&handlekey=register&ajaxmenu=1&action=checkusername&username="+username;
		get = new HttpGet(url2);
		get.addHeader("Referer", Referer);
		get.setHeader("Cookie", cookies);
		httpResponse = httpclient.execute(get);
		html = EntityUtils.toString(httpResponse.getEntity());
		sessionID = httpResponse.getHeaders("Set-Cookie");
		//	this.setCookie(sessionID);
		//	log.info(html);
		//	log.info("------------------end of check username ---------------------------------");
		get.releaseConnection();

		e = form.select("ul input[tabindex=2]").first();
		postparams.put( e.attr("name"), password);//password
		e = form.select("ul input[tabindex=3]").first();
		postparams.put( e.attr("name"), password );//password

		String email= "myemail"+(int)(Math.random()*10000)+"@163.com";
		e = form.select("ul input[type=email]").first();
		postparams.put( e.attr("name"), email);//email
		String url3 = "http://www.sjzyjq.com/forum.php?mod=ajax&inajax=yes&infloat=register&handlekey=register&ajaxmenu=1&action=checkemail&" +
				"email="+email;
		get = new HttpGet(url2);
		get.addHeader("Referer", Referer);
		get.setHeader("Cookie", cookies);
		httpResponse = httpclient.execute(get);
		sessionID = httpResponse.getHeaders("Set-Cookie");
		//		this.setCookie(sessionID);
		html = EntityUtils.toString(httpResponse.getEntity());
		//	log.info(html);
		//	log.info("------------------end of checkemail ---------------------------------");
		get.releaseConnection();

	}

	public void setCookie(Header[] heasers){
		cookies = "";
		for(Header s : sessionID){
			String str = s.toString();
			cookies += str.split(":")[1].split(";")[0]+";";

		}
		//	log.info("setCookie="+cookies);
		//	log.info("------------------end of setCookie ---------------------------------");
	}

	String Referer = "http://www.sjzyjq.com/member.php?mod=register";
	public void SJZYJQ( int number ) throws ClientProtocolException, IOException  {

		String url = "http://www.sjzyjq.com/member.php?mod=register";

		GetCookie(url, number);

		HttpParams  httpparams  = new BasicHttpParams();
		HttpClientParams.setRedirecting(httpparams , true);

		HttpClient client = new DefaultHttpClient(httpparams);   
		HttpPost method = new HttpPost( "http://www.sjzyjq.com/member.php?mod=register&amp;mobile=2" );

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		Set set = postparams.entrySet();
		Iterator it = set.iterator();
		while(it.hasNext()){
			Map.Entry     mapentry =  (Entry) it.next();
			params.add(new BasicNameValuePair( (String) mapentry.getKey(), (String) mapentry.getValue()));
			//	method.getParams().setParameter( (String) mapentry.getKey(), mapentry.getValue() );
			//		log.info( mapentry.getKey() + "="+ mapentry.getValue() );
		}
		method.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
		//	log.info("------------------ postparams ------------------------------");

		//使用系统提供的默认的恢复策略
		//   method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());

		method.addHeader("Referer", Referer);
		method.setHeader("Cookie", cookies);

		HttpResponse httpResponse = client.execute(method);
		//	log.info("status="+httpResponse.getStatusLine());  //打印服务器返回的状态  
		String html = EntityUtils.toString(httpResponse.getEntity());
		Document doc = Jsoup.parse(html);
		int index1 = html.indexOf("alert_error");
		log.info("error="+ html.substring(index1, index1+30));
		Header[] headers = httpResponse.getAllHeaders();
		for(Header h : headers){
			//log.info("header : "+h.toString());
		}
		String key = "感谢您注册";
		int index = html.indexOf(key);
		if(index>0){
			log.info(number+": "+key+" "+this.getUsername()+ html.substring(index, index+50));
		}else{
			log.info(number+": "+" 失败 "+this.getUsername());
		}
		//		log.info("---------------------------------------------------");
		sessionID = httpResponse.getHeaders("Set-Cookie");
		this.setCookie(sessionID);
		//	System.out.println( html );  
		//	log.info("---------------------------------------------------");
		//释放连接  
		method.releaseConnection();

	}

	/**
	 * @return the username
	 */
	public String getUsername() {
		return username;
	}

	/**
	 * @param username the username to set
	 */
	public void setUsername(String username) {
		this.username = username;
	}


}
